using System;
using System.Collections.Generic;
using System.Linq;
using BuildWheel;
using UnityEngine;
using UnityEngine.UIElements;

public class FolderDetailTree : MonoBehaviour
{
    private UIDocument uiroot;
    private TreeView treeView;
    private TextField textField;
    private EnumField enumField;
    public Folders folder;

    public static FolderDetailTree instance;
    private ResEnum selectResType = ResEnum.normal;

    private void Awake()
    {
        instance = this;
    }

    void Start()
    {
        uiroot = GetComponent<UIDocument>();
        treeView = uiroot.rootVisualElement.Q<TreeView>("treeDetail");
        textField = uiroot.rootVisualElement.Q<TextField>("txtSearch");
        enumField = uiroot.rootVisualElement.Q<EnumField>("typeSeach");

        textField.EnableWebGLInput();
        textField.RegisterCallback<ChangeEvent<string>>((evt) => { RefSearch(evt.newValue.ToLower()); });
        enumField.Init(ResEnum.normal);
        enumField.RegisterCallback<ChangeEvent<Enum>>((evt) => { RefType((ResEnum)evt.newValue); });
      
        
        // Callback invoked when the user double clicks an item
        treeView.itemsChosen += (selectedItems) =>
        {
            // Debug.Log("Items chosen: " + string.Join(", ", selectedItems));
            // var select = treeView.GetItemDataForIndex<File>(treeView.selectedIndex);
            // HierarchyTree.Instance.Create(select);
        };
        

// Callback invoked when the user changes the selection inside the TreeView
        treeView.selectedIndicesChanged += (selectedItems) =>
        {
            var select = treeView.GetItemDataForIndex<File>(treeView.selectedIndex);
            if (select != null)
            {
                Inspector.Instance.Ref(select);
            }
        };
        
        treeView.RegisterCallback<MouseDownEvent>(OnMouseClick);
    }

    private void OnMouseClick(MouseDownEvent evt)
    {
        if (evt.button == (int)MouseButton.RightMouse)
        {
            var item = treeView.selectedItem as File;
            
            List<MenuPopupData> ls = new List<MenuPopupData>();
            ls.Add(new MenuPopupData()
            {
                label = "Add to Scene",
                onback = OnAddToSecen,
                obj = item
            });
            MenuPopup.Instance.Show(evt.mousePosition, ls);
        }
    }

    private void OnAddToSecen(MenuPopupData obj)
    {
        HierarchyTree.Instance.Create(obj.obj as File);
    }

    void RefType(ResEnum newRes)
    {
        selectResType = newRes;
        if (newRes == ResEnum.normal)
        {
            Ref();
        }
        else
        {
            RefView(FoldersMgr.fileObject.fileDicT[newRes.ToString()]);
        }
    }

    List<File> searchFiles = new List<File>();

    void RefSearch(string searchKey)
    {
        if (string.IsNullOrEmpty(searchKey))
        {
            Ref();
            return;
        }

        searchKey = searchKey.ToLower();

        var dic = FoldersMgr.fileObject.fileDicT;
        searchFiles.Clear();
        foreach (var item in dic)
        {
            var temp = item.Value;
            for (int i = 0; i < temp.Count; i++)
            {
                if (temp[i].nameToLow.StartsWith(searchKey))
                {
                    searchFiles.Add(temp[i]);
                }
            }
        }

        RefView(searchFiles);
    }

    void Ref()
    {
        searchFiles.Clear();
        Ref(folder);
    }

    public void Ref(Folders _folder)
    {
        this.folder = _folder;
        treeView.Clear();
        RefView(folder.files);
    }

    void RefView(List<File> files)
    {
        treeView.Clear();
        if (files == null) return;

        int fileCcount = files.Count;
        if (fileCcount == 0) return;
        
        var items = new List<TreeViewItemData<File>>(fileCcount);
        int index = 0;

        for (int j = 0; j < fileCcount; j++)
        {
            var child = files[j];
            index += 1;
            var item = new TreeViewItemData<File>(index, child);
            items.Add(item);
        }


        Func<VisualElement> makeItem = () => new Label();

        Action<VisualElement, int> bindItem = (e, i) =>
        {
            var item = treeView.GetItemDataForIndex<File>(i);
            (e as Label).text = $"{item.n}.{item.s}";
        };
        treeView.SetRootItems(items);
        treeView.makeItem = makeItem;
        treeView.bindItem = bindItem;
        treeView.selectionType = SelectionType.Multiple;
        treeView.Rebuild();
    }
}